import cv2
import numpy as np
from PyQt5.QtCore import QThread, pyqtSlot, QVariant, Qt, pyqtSignal
from PyQt5.QtGui import QImage
from PyQt5 import QtGui


class CameraThread(QThread):
    """
        利用OPENCV打开摄像头，并把图像发送给QT窗口的线程类
        该类同时作为其它摄像头类的基类
    """
    changePixmap = pyqtSignal(QImage)

    def __init__(self, parent=None, camera=0):
        super().__init__(parent)
        self.camera = camera
        self.cap = cv2.VideoCapture(self.camera)
        self.loop = True

    @pyqtSlot()
    def do_stop(self):
        self.loop = False

    def run(self):
        while self.loop:
            ret, frame = self.cap.read()
            if not ret:
                print("摄像头出错！")
                break
            frame = self.process_image(frame)
            self.send_image_to_gui(frame)
        if not self.loop:
            self.cap.release()

    def process_image(self, frame):
        return frame

    def send_image_to_gui(self, frame):
        rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgbImage.shape
        bytesPerLine = ch * w
        convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
        p = convertToQtFormat.scaled(320, 240, Qt.KeepAspectRatio)
        self.changePixmap.emit(p)
